package com.gitee.cui.netty.handler;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.embedded.EmbeddedChannel;
import org.junit.Test;

/**
 * 出站生命周期测试类
 * @author cuiqingqiang
 * @version 1.0
 * @date 2021/10/21 17:13
 **/
public class OutboundHandlerTest {

    @Test
    public void outboundHandlerTest() {
        OutboundHandler outboundHandler = new OutboundHandler();
        ChannelInitializer<EmbeddedChannel> channelInitializer = new ChannelInitializer<EmbeddedChannel>() {

            @Override
            protected void initChannel(EmbeddedChannel ch) throws Exception {
                ch.pipeline().addLast(outboundHandler);
            }
        };
        EmbeddedChannel embeddedChannel = new EmbeddedChannel(channelInitializer);
        // 测试出站写入
        ByteBuf buffer = Unpooled.buffer();
        buffer.writeInt(1);

        ChannelFuture channelFuture = embeddedChannel.pipeline().writeAndFlush(buffer);
        channelFuture.addListener(future -> {
           if (future.isSuccess()) {
               System.out.println("write is finished");
           }
           embeddedChannel.close();
        });

        try {
            Thread.sleep(Integer.MAX_VALUE);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
